//APP更新
import configService from '@/common/service/config.service.js'
export default function appUpdate() {
	console.log("plus.runtime.appid="+plus.runtime.appid+" 0");
	console.log("plus.runtime.version="+plus.runtime.version+" 1");
	console.log("plus.device.imei="+plus.device.imei+" 2");
	uni.request({
		url: configService.apiUrl +
			'/app/appUpdate/queryByAppid', // 'http://app.jeecg.com/update.json', //检查更新的服务器地址
		data: {
			appid: plus.runtime.appid,
			version: plus.runtime.version,
			imei: plus.device.imei,
			tenantId:1005
		},
		success: (res) => {
			console.log("successsuccesssuccesssuccesssuccesssuccesssuccess",res);
			plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {
				let client_version = wgtinfo.version
				console.log("client_version",client_version);
				var flag_update = client_version.split(".").splice(0, 2).join(".") != res.data.result.version.split(".").splice(0, 2)
					.join(".")
				console.log("flag_update",flag_update);
				var flag_hot = (Number(client_version.split(".")[2]) < Number(res.data.result.version.split(".")[2])) & !flag_update
				console.log(client_version)
				console.log(flag_update)
				console.log(flag_hot)

				if (flag_update || flag_hot) {
					// 提醒用户更新
					uni.showModal({
						title: '更新提示',
						content: res.data.result.note,
						success: (showResult) => {
							if (showResult.confirm && flag_update) {
								plus.nativeUI.toast("正在准备环境，请稍后!");
								console.log(configService.staticDomainURL+'/'+res.data.result.url);
								var dtask = plus.downloader.createDownload(configService.staticDomainURL+'/'+res.data.result.url, {
									method: 'GET',
									filename: '_doc/update/'
								}, function(d, status) {
									if (status == 200) {
										var path = d.filename; //下载apk
										plus.runtime.install(path); // 自动安装apk文件
									} else {
										plus.nativeUI.alert('版本更新失败:' + status);
									}
								});
								try {
									dtask.start(); // 开启下载的任务
									var prg = 0;
									var showLoading = plus.nativeUI.showWaiting(
										"正在下载"); //创建一个showWaiting对象 
									dtask.addEventListener('statechanged', function(
										task,
										status
									) {
										console.log("task.downloadedSize="+task.downloadedSize);
										console.log("task.totalSize="+task.totalSize); 
										// 给下载任务设置一个监听 并根据状态  做操作 
										switch (task.state) {
											case 1:
												showLoading.setTitle("正在下载");
												break;
											case 2:
												showLoading.setTitle("已连接到服务器");
												break;
											case 3:
												prg = parseInt(
													(parseFloat(task.downloadedSize) /
														parseFloat(task.totalSize)) *100);
												showLoading.setTitle("  正在下载" +
													prg + "%  ");
												break;
											case 4:
												plus.nativeUI.closeWaiting();
												//下载完成
												break;
										}
									});
								} catch (err) {
									plus.nativeUI.closeWaiting();
									uni.showToast({
										title: '更新失败-03',
										mask: false,
										duration: 1500
									});
								}
							} else if (showResult.confirm && flag_hot) {
								console.log("res.data.result.wgturl=",configService.staticDomainURL+'/'+res.data.result.wgturl);
								const downloadTask = uni.downloadFile({
									url: configService.staticDomainURL+'/'+res.data.result.wgturl,
									success: (downloadResult) => {
										console.log(downloadResult.tempFilePath)
										if (downloadResult.statusCode === 200) {
											plus.nativeUI.closeWaiting();
											plus.nativeUI.toast(`正在热更新!${res.data.result.version}`);
											plus.runtime.install(downloadResult.tempFilePath, {
												force: false
											}, function() {
												plus.nativeUI.toast("热更新成功");
												plus.runtime.restart();
											}, function(e) {
												console.log(e)
												plus.nativeUI.toast(`热更新失败:${e.message}`);
											});
										}
									}
								});
								var showLoading = plus.nativeUI.showWaiting(
									"正在下载"); //创建一个showWaiting对象 
								// 监听进度
								downloadTask.onProgressUpdate((res) => {
								  console.log('下载进度', res.progress);
								  console.log('已经下载的数据长度', res.totalBytesWritten);
								  console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
								  var prg = 0;
								  // 更新进度条
								  // 假设 progressBar 是进度条组件的引用
								  // this.progressBar.percent = res.progress / 100; // 假设进度条的取值范围是0-1
								  showLoading.setTitle("  正在下载" +
								  	res.progress + "%  ");
								});
							}
						}
					})
				} else if (flag_hot) {
					// console.log("res.data.result.wgturl=",configService.staticDomainURL+'/'+res.data.result.wgturl);
					// uni.downloadFile({
					// 	url: configService.staticDomainURL+'/'+res.data.result.wgturl,
					// 	success: (downloadResult) => {
					// 		console.log(downloadResult.tempFilePath)
					// 		if (downloadResult.statusCode === 200) {
					// 			plus.nativeUI.toast(`正在热更新!${res.data.result.version}`);
					// 			plus.runtime.install(downloadResult.tempFilePath, {
					// 				force: false
					// 			}, function() {
					// 				plus.nativeUI.toast("热更新成功");
					// 				plus.runtime.restart();
					// 			}, function(e) {
					// 				console.log(e)
					// 				plus.nativeUI.toast(`热更新失败:${e.message}`);
					// 			});
					// 		}
					// 	}
					// });
				}
			});
		}
	})
}